const baseUrl = 'http://127.0.0.1:8000'

function request(method, url, data = {}, header = {}) {
	console.log(url, "123")
	// if (!hasTokenOrIsLogin(url)) {
	// 	uni.navigateTo({
	// 		url: '/pages/login/login'
	// 	})
	// 	return; // 如果没有token或未登录，不发送请求
	// }
	
	return new Promise((resolve, reject) => {
		showLoading(); // 显示加载动画
		uni.request({
			url: baseUrl + url,
			data,
			method: method,
			header: {
				Authorization: uni.getStorageSync('token'), // 添加token到请求头
				...header
			},
			success: (res) => handleSuccess(res, resolve, reject), // 请求成功处理
			fail: (err) => handleError(err, reject) // 请求失败处理
		})
	})
}

function showLoading() {
	uni.showLoading({
		title: '加载中'
	})
}

function hideLoading() {
	uni.hideLoading()
}

function hasTokenOrIsLogin(url) {
	// 已有token，或者当前是登录接口
	return uni.getStorageSync('token') || url === '/user-service/user/login' || url ===
		'/user-service/user/phoneLogin' || url.includes('/user-service/user/getPhoneCode') || 
		url === '/user-service/user/resetPassword' || url === '/user-service/user/register'; // 添加重置密码和注册接口
}

function handleSuccess(response, resolve, reject) {
	hideLoading(); // 隐藏加载动画
	const {
		statusCode,
		data: resData
	} = response;
	const {
		code,
		data: innerData,
		message
	} = resData;

	if (statusCode === 200 && code === 1) {
		resolve(innerData); // 成功时返回数据
	} else if (code === 401) {
		handleUnauthorizedAccess(); // 处理未授权访问
		reject(message);
	} else {
		showErrorMessage(message); // 提示错误信息
		reject(message);
	}
}

function handleError(error, reject) {
	hideLoading(); // 隐藏加载动画
	console.error(error);
	reject();
}

function handleUnauthorizedAccess() {
	uni.clearStorage(); // 清除本地存储
	// uni.reLaunch({
	// 	url: '/pages/home/home' // 重启小程序并返回到首页
	// });
	uni.showModal({
		title: "提示",
		content: "请登录",
		showCancel: false,
		success() {
			setTimeout(() => {
				uni.navigateTo({
					url: "/pages/login/login",
				})
			}, 1000);
		},
	});
}

function showErrorMessage(msg) {
	uni.showToast({
		title: msg,
		icon: "none",
		duration: 2000
	})
}

export default {
	get(url, data, header) {
		return request('GET', url, data, header);
	},
	post(url, data, header) {
		return request('POST', url, data, header);
	}
}